package com.zpy.SmartChargeStation.netty.server.websocket;

import com.zpy.SmartChargeStation.netty.server.handlers.*;
import com.zpy.SmartChargeStation.protocol.protobuf.ChargingCmdProtobuf;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;


/**
 * description: 自定义的通道初始化
 */

@Slf4j
public class ImoocChannelInit extends ChannelInitializer<SocketChannel> {
    /**
     * description: 通道初始化
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        //取出ChannelPipeline
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline
                //超时监听
                .addLast(new IdleStateHandler(300,300,300, TimeUnit.SECONDS))
                //自定义的超时处理逻辑
                .addLast(new ImoocServerHeartBeatHandler())
                //对HTTP协议的解析
                .addLast(new HttpServerCodec())
                //处理HTTP 的POST请求
                .addLast(new HttpObjectAggregator(65536))

                //对WebSocket协议解析
                .addLast(new WebSocketServerProtocolHandler(
                        "/ws"))

                //消息类型转换：将WebSocketFrame转换为BinaryWebSocketFrame
                .addLast(new ProtoMsgToMsgHandler())

                //(接收数据) Protobuf反序列化
                .addLast(new ProtobufDecoder(ChargingCmdProtobuf.ChargingCmd.getDefaultInstance()))

                //(发送数据) Protobuf序列化
                //.addLast(new ProtobufEncoder())

                //添加处理器
                .addLast(new ImoocWebSocketInboundHandler())

                //对Protobuf反序列化进行业务处理
                .addLast(new ProtobufHandler())

                //给小程序推送WebSocket消息
                .addLast(new ImoocWebSocketOutboundHandler())
        ;
    }
}
